//
//  ZSJPushManager.m
//  VideoExam
//
//  Created by apple on 2020/6/18.
//

#import "ZSJPushManager.h"
#import <JPUSHService.h>
#import "PushModel.h"
#import "OrderDetailsController.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


static ZSJPushManager * jpushManager;

@interface ZSJPushManager ()<JPUSHRegisterDelegate>

@end

@implementation ZSJPushManager


+ (instancetype)shareManager {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
      jpushManager = [[ZSJPushManager alloc] init];
  });
  return jpushManager;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        _app_badge_Number = 0;
    }
    return self;
}
//app 角标数处理
+ (void)app_badge_handler {
    [ZSJPushManager shareManager].app_badge_Number =0;
    NSInteger number = [ZSJPushManager shareManager].app_badge_Number;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:number];
}


//
+ (void)init_jpush_sdk_launchOptions:(NSDictionary *)launchOptions {

    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
   entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    
    ZSJPushManager * jpushManager = [ZSJPushManager shareManager];
    
   [JPUSHService registerForRemoteNotificationConfig:entity delegate:jpushManager];//启动sdk
    
    /*!
    * @abstract 启动SDK
    *
    * @param launchingOption 启动参数.
    * @param appKey 一个JPush 应用必须的,唯一的标识. 请参考 JPush 相关说明文档来获取这个标识.
    * @param channel 发布渠道. 可选.
    * @param isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
    *                     App 证书环境取决于profile provision的配置，此处建议与证书环境保持一致.
    * @param advertisingId 广告标识符（IDFA） 如果不需要使用IDFA，传nil.
    *
    * @discussion 提供SDK启动必须的参数, 来启动 SDK.
    * 此接口必须在 App 启动时调用, 否则 JPush SDK 将无法正常工作.
    */
   [JPUSHService setupWithOption:launchOptions appKey:Jpush_key
                 channel:@"App Store"
        apsForProduction:YES
   advertisingIdentifier:nil];
   
   //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
      if(resCode == 0){
          [ZSJPushManager shareManager].registrationId = registrationID;
        NSLog(@"registrationID获取成功：%@",registrationID);
      }
      else{
        NSLog(@"registrationID获取失败，code：%d",resCode);
      }
    }];
}


//注册设备token
+ (void)registerDeviceToken:(NSData *)deviceToken {
     [JPUSHService registerDeviceToken:deviceToken];
}


#pragma mark JPUSHRegisterDelegate

//前台收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler  API_AVAILABLE(ios(10.0)){
  NSDictionary * userInfo = notification.request.content.userInfo;

//  UNNotificationRequest *request = notification.request; // 收到推送的请求
//  UNNotificationContent *content = request.content; // 收到推送的消息内容
//  NSNumber *badge = content.badge;  // 推送消息的角标
//  NSString *body = content.body;    // 推送消息体
//  UNNotificationSound *sound = content.sound;  // 推送消息的声音
//  NSString *subtitle = content.subtitle;  // 推送消息的副标题
//  NSString *title = content.title;  // 推送消息的标题
   NSLog(@"通知信息点击通知进入app %@",userInfo);
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
      
//      UIApplicationState state = [UIApplication sharedApplication].applicationState;
//      if(state == UIApplicationStateBackground){
//
//             NSLog(@"后台===");
//
//      }else if (state == UIApplicationStateActive){
//
//             NSLog(@"前台==");
//
//      }
    NSLog(@"iOS10 前台收到远程通知");
  }

  completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}
//后台收到通知 或者 程序没有运行 点击通知会调用这个方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
  NSDictionary * userInfo = response.notification.request.content.userInfo;
//  UNNotificationRequest *request = response.notification.request; // 收到推送的请求
//  UNNotificationContent *content = request.content; // 收到推送的消息内容
//
//  NSNumber *badge = content.badge;  // 推送消息的角标
//  NSString *body = content.body;    // 推送消息体
//  UNNotificationSound *sound = content.sound;  // 推送消息的声音
//  NSString *subtitle = content.subtitle;  // 推送消息的副标题
//  NSString *title = content.title;  // 推送消息的标题
    NSLog(@"点击了通知信息=== %@",userInfo);
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
      NSLog(@"点击了通知信息=22==");
      [self performSelector:@selector(pushu_handler_results:) withObject:userInfo afterDelay:0.5];
  }
  completionHandler();  // 系统要求执行这个方法
}

- (void)pushu_handler_results:(NSDictionary *)results {
    PushModel *model =[PushModel yy_modelWithJSON:results];
    [ZSJPushManager shareManager].app_badge_Number = [model.aps.badge intValue];//app角标处理
    [ZSJPushManager app_badge_handler];
    
    OrderDetailsController * vc = [[OrderDetailsController alloc] init];
    vc.orderId =model.orderId;
    UIViewController * currentVc =[AppTools zs_getCurrentViewController];
    [currentVc.navigationController pushViewController:vc animated:YES];
}

/////*s
// * @brief handle UserNotifications.framework [openSettingsForNotification:]
// * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心
// * @param notification 当前管理的通知对象
// */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification  API_AVAILABLE(ios(10.0)){
    
}

/**
 * 监测通知授权状态返回的结果
 * @param status 授权通知状态，详见JPAuthorizationStatus
 * @param info 更多信息，预留参数
 */
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
    
}
@end
